package com.sunnybear.framework.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.accessibility.AccessibilityEvent;

import com.sunnybear.framework.R;
import com.sunnybear.framework.databinding.DurationToastLayoutBinding;
import com.sunnybear.framework.library.base.BaseDialogFragment;
import com.sunnybear.framework.tools.ActivityStackManager;
import com.sunnybear.framework.tools.log.Logger;
import com.trello.rxlifecycle2.LifecycleProvider;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.RxLifecycle;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.android.RxLifecycleAndroid;

import java.util.concurrent.TimeUnit;

import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import io.reactivex.Flowable;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.BehaviorSubject;

/**
 * <p>
 *  2018/8/1.
 */
public class ToastDialogFragment extends BaseDialogFragment<DurationToastLayoutBinding> implements LifecycleProvider<ActivityEvent> {

    public static final String KEY_TEXT = "key_text";
    public static final String KEY_DURATION = "key_duration";

    private final BehaviorSubject<ActivityEvent> lifecycleSubject = BehaviorSubject.create();


//    public static final String KEY_IMG = "key_img";
//
//    public static final String KEY_TYPE = "key_type";

    @Override
    protected int getLayoutId() {
        return R.layout.duration_toast_layout;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.Dialog_toast);
        setCancelable(false);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onBundle(Bundle args) {
        String text = args.getString(KEY_TEXT);
        mViewDataBinding.toastText.setText(text);
//        int resId = args.getInt(KEY_IMG);
//        if (resId > 0) {
//            mViewDataBinding.toastIcon.setImageResource(resId);
//        }
        mViewDataBinding.toastText.setBackgroundResource(R.drawable.toast_frame);

        long duration = args.getLong(KEY_DURATION);
        duration = Math.max(duration, 1000);

        //启动倒计时
        Flowable.timer(duration - 300, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread())
                .compose(ToastDialogFragment.this.<Long>bindToLifecycle())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        Logger.d("zxl", "toast width:" + mViewDataBinding.getRoot().getMeasuredWidth() + "|" + mViewDataBinding.llFather.getMeasuredWidth());
                        //淡出
//                        ObjectAnimator alphaFadeOut = ObjectAnimator
//                                .ofFloat(mViewDataBinding.toastText, "alpha", 1, 0);
//                        alphaFadeOut.setDuration(300);
//                        alphaFadeOut.addListener(new AnimatorListenerAdapter() {
//                            @Override
//                            public void onAnimationEnd(Animator animation) {
//                                dismiss();
//                            }
//                        });
//                        alphaFadeOut.start();
                        dismiss();
                    }
                });
    }

    @Override
    @NonNull
    @CheckResult
    public final Observable<ActivityEvent> lifecycle() {
        return lifecycleSubject.hide();
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindUntilEvent(@NonNull ActivityEvent event) {
        return RxLifecycle.bindUntilEvent(lifecycleSubject, event);
    }

    @Override
    @NonNull
    @CheckResult
    public final <T> LifecycleTransformer<T> bindToLifecycle() {
        return RxLifecycleAndroid.bindActivity(lifecycleSubject);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(getActivity(), getTheme()) {
            @Override
            public boolean dispatchTouchEvent(@NonNull MotionEvent event) {
                Activity current = ActivityStackManager.getInstance().top();
                Logger.d("zxl", "toast test:" + current);
                if (current != null) {
                    return current.dispatchTouchEvent(event);
                }
                return super.dispatchTouchEvent(event);
            }

            @Override
            public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
                Activity current = ActivityStackManager.getInstance().top();
                Logger.d("zxl", "toast test:" + current);
                if (current != null) {
                    return current.dispatchKeyEvent(event);
                }
                return super.dispatchKeyEvent(event);
            }

            @Override
            public boolean dispatchGenericMotionEvent(@NonNull MotionEvent event) {
                Activity current = ActivityStackManager.getInstance().top();
                Logger.d("zxl", "toast test:" + current);
                if (current != null) {
                    return current.dispatchGenericMotionEvent(event);
                }
                return super.dispatchGenericMotionEvent(event);
            }

            @Override
            public boolean dispatchPopulateAccessibilityEvent(@NonNull AccessibilityEvent event) {
                Activity current = ActivityStackManager.getInstance().top();
                Logger.d("zxl", "toast test:" + current);
                if (current != null) {
                    return current.dispatchPopulateAccessibilityEvent(event);
                }
                return super.dispatchPopulateAccessibilityEvent(event);
            }


            @Override
            public boolean dispatchTrackballEvent(@NonNull MotionEvent event) {
                Activity current = ActivityStackManager.getInstance().top();
                Logger.d("zxl", "toast test:" + current);
                if (current != null) {
                    return current.dispatchTrackballEvent(event);
                }
                return super.dispatchTrackballEvent(event);
            }
        };
        dialog.getWindow().getAttributes().windowAnimations = R.style.toastDialogAnim;
        return dialog;
    }

}
